<?php
// 商品相关管理
namespace NewAdmin\Controller;
use Think\Controller;
class ShopController extends CommonController {

    function _initialize() {
        parent::_initialize();
        $this->ad_model = M("group_ad");
        $this->thumbPath=__ROOT__.'data/upload/';
    }

	/**
	 * 商品列表
	 */
    public function index(){
    	$shop	=	D('shop');
        
    	$userArray	=	$this->userArray;
        $store = D("store");//店铺信息
    	//$title	=	I('get.title');
    	$title = $_GET['title'];
		
		if($title === iconv('utf-8', "utf-8", iconv("utf-8", 'utf-8', $title))){
			$title=$title;
		}else{
			$title= iconv("gbk","utf-8",$title);
		}
        if( $title ){
        	$where['title'] = array('like',"%$title%");
        }
        if(I('get.type_id')){
        	$type_id=I('get.type_id');
        	$where['_string']="FIND_IN_SET($type_id,type_id)";
        }
        
        if(I('get.id')){
        	$id=I('get.id');
        	$where['id']=$id;
        }
        
        if(I('get.status_id')>0){
        	$status_id=I('get.status_id')-1;
        	if($status_id!=3){
        		$where['ishidden']=$status_id;
        	}else{
        		$where['num']=0;
        	}
        	
        }
       
		
        $_GET['title']	=	implode('_',$titleArray);
	    $count      = $shop->where($where)->count();
	    $this->assign('count',$count);
	    $Page       = new \Think\Page($count,25);// 实例化分页类 传入总记录数
	  	
		$Page->setConfig('header','条记录');
	    $Page->setConfig('prev','上一页');
	    $Page->setConfig('next','下一页');
	    $show = $Page->show(); // 分页显示输出
    	$array	=	$shop->field("*")->where($where)->order('id DESC')->limit($Page->firstRow.','.$Page->listRows)->select();
    	
        //查询商品所属的店铺  添加时间：2016-12-23  添加人：毕玉
        foreach ( $array AS $key=>$row ){
            $storeinfo = $store->field("title")->where("id=".$row["store_id"])->find();
            $array[$key]["storename"] =$storeinfo["title"];
		}
        $this->assign('page',$show);// 赋值分页输出
        $this->assign('array',$array);
      
      	$ticketType = D('TicketType');
		$ticketTypeArray	=	$ticketType->field('id,name,bid,bids')->where(' ishidden = 0 ' )->select();
        $this->assign('ticketTypeArray',$ticketTypeArray);

		$classTree = catetree($ticketTypeArray);
		
		
		$this->assign('classTree',$classTree);
        $this->assign('title','商品列表');
		$this->display();
    }
	function checkshop(){
		$shop	=	D('shop');
		$data=I('get.');
		$shop->save($data);
	
		$this->redirect('Shop/index');
	}
    /**
     * 添加
    */
    function add(){
    	if( $_GET['id'] ){
    		$this->assign('title','修改商品');
        }else{
    		$this->assign('title','添加商品');
    	}

        file_put_contents("shop.txt", date("Y-m-d H:i:s") . "coupon_goods_sql   " . print_r($_POST, true) . "\r\n", FILE_APPEND);
        $current= M()->field('shop.*,ShopContent.content,ShopContent.config,ShopContent.gallery,ShopContent.story_content,ShopContent.story_title,story_img,story_exprot,brand.name AS brand_name,stroe.title as btitle')
            ->table(' __SHOP__ AS shop ')
            ->join(' LEFT JOIN __SHOP_CONTENT__ AS ShopContent ON ( ShopContent.shop_id = shop.id ) ')
            ->join(' LEFT JOIN __BRAND__ AS brand ON ( brand.id = shop.brand_id ) ')
            ->join(' LEFT JOIN __STORE__ AS stroe ON ( stroe.id = shop.store_id ) ')
            ->where('shop.id = '.$_GET['id'])->find();
       
        $this->assign('current',$current);
       
        //当前配置属性
        $currentConfig	=	json_decode($current['config'],true);
        $this->assign('currentConfig',$currentConfig);
        //获取一级分类列表
        $ticketType =   D('TicketType');
        $ticketTypeArray=   $ticketType->where(' ishidden = 0 AND bid = 0')->order(' sort ASC ')->select();
        $this->assign('ticketTypeArray',$ticketTypeArray);
        //获取品牌列表
        $brand =   D('Brand');
        $where	=	'ishidden = 0';
        $brandArray    =   $brand->field('id,name')->where($where)->order(' name ASC')->select();
        $this->assign('brandArray',$brandArray);

        //获取店铺列表
        $store =   D('store');
      
        $Storearray    =   $store->field('id,title')->order(' id asc')->select();
        $this->assign('Storearray',$Storearray);
       
        if( $_GET['id'] ){
            $ticketConfig   =   D('TicketConfig');
            $arrayFlag  =   clearArrayNull(explode(',',$current['type_id']));
            $currentTypeId  =   implode(',',$arrayFlag);
            $where  =   'ishidden = 0 AND is_end=1 AND id IN ( '.$currentTypeId.' )';
            $typeArray  =   $ticketType->where($where)->order('id DESC')->select();
            $type_ids;
            //去属性重复
            foreach ($typeArray as $key => $value) {
                if(!in_array($value['type_id'], $type_ids)){
                     $type_ids[$key]=$value['type_id'];
                }
            }
            $configArrays;

            foreach ($type_ids as $key => $value) {
                 $newwhere     =   'ishidden = 0 AND type_id IN ( '.$value.' )';
                 $configArray   =   $ticketConfig->where($newwhere)->order('id DESC')->select();
                 if($configArrays){
                    $configArrays =array_merge($configArrays,$configArray);
                 }else{
                    $configArrays =$configArray;
                 }
                  
                
            }
        
            $this->assign('configArray',$configArrays);

	        //获取当前商品最后分类
	        $currentTypeArray	=	$ticketType->field('id,name')->where(' id IN ('.$currentTypeId.') AND is_end = 1')->select();
			
	        $this->assign('currentTypeArray',$currentTypeArray);
        }

        $SKU_View=$this->CreateSKUView();
        
        $this->assign('SKU_View',$SKU_View);

	
		$this->display();
    }
   

    /**
     * ajax获取商品分类
     */
    function ajaxGetTicketType(){
    	//获取子分类列表
    	$ticketType =   D('TicketType');
    	$where	=	' ishidden = 0 AND bid = '.I('get.type_id');
    	$where	.=	I('get.keywords')?' AND name LIKE "%'.I('get.keywords').'%"':'';
    	$ticketTypeArray=   $ticketType->where($where)->order(' sort ASC ')->select();
    	$string	=	count($ticketTypeArray).'|||<div class="fl subtype">
    	<ul>';
    	if( $ticketTypeArray ){
    		foreach ( $ticketTypeArray AS $key=>$row ){
    			$string	.=	'<li data="'.$row['id'].'">'.$row['name'].'></li>';
    		}
    	}
    	$string	.=	'</ul>
    	</div>';
    	echo $string;
    }

    /**
     * ajax获取商品品牌
     */
    function ajaxGetBrand(){
    	//获取子分类列表
    	$brand =   D('Brand');
    	$where	=	' ishidden = 0 ';
    	$where	.=	I('get.keywords')?' AND name LIKE "%'.I('get.keywords').'%"':'';
    	$where	.=	I('get.is_for_recycle')?' AND is_for_recycle = "1"':'';
    	$brandArray=   $brand->where($where)->order(' sort ASC ')->select();
    	$string	=	'<div class="fl subtype">
    	<ul>';
    	if( $brandArray ){
    		foreach ( $brandArray AS $key=>$row ){
    			$string	.=	'<li data="'.$row['id'].'">'.$row['name'].'</li>';
    		}
    	}
    	$string	.=	'</ul>
    	</div>';
    	echo $string;
    }

    /**
     * ajax获取属性配置
     */
    function ajaxGetConfig(){
    	$id	=	I('get.type_id');
        $ticketType=M('ticket_type');
        $where  =   'id IN ( '.$id.' )';
        $t_type=$ticketType->where($where)->select();
        $type_ids;
        //去属性重复
        foreach ($t_type as $key => $value) {
            if(!in_array($value['type_id'], $type_ids)){
                 $type_ids[$key]=$value['type_id'];
            }
        }
        $type_id=implode(',',$type_ids);
        //获取配置属性列表
        $ticketConfig   =   D('TicketConfig');
        $where 	=   'ishidden = 0 AND type_id IN ( '.$type_id.' ) ';
    	$configArray	=	$ticketConfig->field('id,title,is_write,content')->where($where)->order('id DESC')->select();
    	$string	=	'';
    	if( $configArray ){
    		foreach ( $configArray AS $key=>$row ){
    			$is_write	=	$row['is_write'] == '1'?'text':'hidden';
    			$string	.=	'<div><span>'.$row['title'].':</span>
			    				<input name="config[]" type="hidden" value="'.$row['id'].','.$row['title'].'" >
			    				<input name="config'.$row['id'].'" id="config'.$row['id'].'" type="'.$is_write.'" value="" > ';
    			$subArray	=	explode(',',$row['content']);
              
    			if( $subArray ){
    				foreach ( $subArray AS $key=>$row1 ){
    					if( !$row1 ){ continue; }
    					$string	.=	'<span class="btn  btn-xs config'.$row['id'].'" data="'.$row['id'].'">'.$row1.'</span> ';
    				}
    			}
    			$string	.=	'</div><div class="space-4"></div>';
    		}
    	}
    	echo $string;
    	die();
       
    }

    /**
     * 添加保存
    */
    function save(){
    
        $shop   =   D('shop');
        $ticketType	 =		D('TicketType');
        $ShopContent   =   D('ShopContent');
     
	    //处理分类ID问题
        if( I('post.type_id') ){
        	$type_id	=	implode(',',I('post.type_id'));
        	$ticketTypeArray	=	$ticketType->field('bids')->where(' id IN ('.$type_id.') ')->select();
        	if( $ticketTypeArray ){
        		$flag	=	'';
        		foreach ( $ticketTypeArray AS $key=>$row ){
        			$flag.=	$row['bids'].',';
        		}
        	}
        	$flagArray	=	explode(',',$flag);
        	$arrayFlag		=	clearArrayNull($flagArray);
        	$typeIdFlag	=	implode(',',$arrayFlag);
        }
        $id                                 =   $_POST['id'];
        $new_data['title']					=	I('post.title');
        $new_data['keywords']				=	I('post.keywords');
        $new_data['description']            =   I('post.description');
        $new_data['image']					=	I('post.thumb');
        $new_data['type_id']				=	','.$typeIdFlag.',';
        $new_data['brand_id']               =   I('post.brand_id');
        $new_data['store_id']          =   I('post.store_id');

        $new_data['click_num']               =   I('post.click_num');
        $new_data['price']                  =   I('post.price');
        $new_data['oprice']                 =   I('post.oprice');
        $new_data['start']                  =   strtotime(I('post.start'));
        $new_data['end']                    =   I('post.end')?strtotime(I('post.end')):''; 

        $new_data['num']                    =   I('post.num');
        $new_data['xz_num']                 =   I('post.xz_num');
        $new_data['qp_num']                 =   I('post.qp_num');
        $new_data['sale_num']               =   I('post.sale_num');
        $new_data['px_id']                  =   I('post.px_id');
        //$new_data['redenvelope']            =   I('post.redenvelope');
       $new_data['dikouquan']            =   I('post.dikouquan');
      
        $new_data['isindex']			    =	I('post.isindex');

        $new_data['mian_send']             =   I('post.mian_send');
        $new_data['tuanselect']             =   I('post.tuanselect');
        $new_data['tuan_num']               =   I('post.tuan_num');
        $new_data['tuan_price']             =   I('post.tuan_price');
        $new_data['tuan_buynum']            =   I('post.tuan_buynum');
        $new_data['tuanz_buysale']          =   I('post.tuanz_buysale');
		 $new_data['tuanz_starttime']          =   I('post.tuanz_starttime')?strtotime(I('post.tuanz_starttime')):''; 
        $new_data['tuanz_endtime']          =   I('post.tuanz_endtime')?strtotime(I('post.tuanz_endtime')):''; 
        if($new_data['dikouquan']>$new_data['price']){
			 echo '0|||抵扣券不能大于商品售价';die();
		}
		if($new_data['redenvelope']>$new_data['price']){
			 echo '0|||红包不能大于商品售价';die();
		}
        if($new_data['store_id']=='0'){
             echo '0|||请选择所属店铺';die();
        }
        
        if($new_data['image']==null){
             echo '0|||请上传商品图片';die();
        }

        if($new_data['brand_id']=='0'){
             echo '0|||请选择商品品牌';die();
        }

        if($new_data['tuanselect'] =='1'&&$new_data['tuan_num']==null){
            echo '0|||请输入开团人数';die();
        }
        if($new_data['tuanselect'] =='1'&&$new_data['tuan_price']==null){
            echo '0|||请输入团购价格';die();
        }
        if($new_data['tuanselect'] =='1'&&$new_data['tuan_buynum']==null){
            echo '0|||请输入限制购买数量';die();
        }
//      if($new_data['tuanselect'] =='1'&&$new_data['tuanz_buysale']==null){
//          echo '0|||请输入团长优惠';die();
//      }
		 if($new_data['tuanselect'] =='1'&&$new_data['tuanz_starttime']==null){
            echo '0|||请输入开团开始时间';die();
        }
        if($new_data['tuanselect'] =='1'&&$new_data['tuanz_endtime']==null){
            echo '0|||请输入开团结束时间';die();
        }

       

        //处理配置属性
        $configArray	=	I('post.config');

        $new_data['search_tag']='';
        $arrayFlag	=	array();
        if( $configArray ){
        	foreach( $configArray AS $key=>$row ){
        		$flag	=	explode(',',$row);
        		$arrayFlag[$flag[0]]['title']				=	urlencode($flag[1]);
        		$arrayFlag[$flag[0]]['content']		=	urlencode(I('post.config'.$flag[0]));
                $new_data['search_tag'].=I('post.config'.$flag[0]).',';
        	}
        }
        
        $new_data1['config']	=urldecode(	json_encode($arrayFlag));
        $new_data1['content']	=	preg_replace('/<br \/>/','',$_POST['content']);
        $new_data1['story_content']	=	preg_replace('/<br \/>/','',I('post.story_content'));
        $new_data1['story_title']	=	I('post.story_title');
        $new_data1['story_img']	=	I('post.story_img');
        $new_data1['story_exprot']	=	I('post.story_exprot');
		$new_data1['gallery']	=	I('post.gallery');
		$new_data1['story_time']	=	time();
        //处理sku
        //库存
        $SKU_Stock=I('post.SKU_Stock');
        //价格
        $SKU_Price=I('post.SKU_Price',0,'floatval');

        //团购价格

        $SKU_Price_tuan=I('post.SKU_Price_tuan',0,'floatval');
        //SKU编号
        $SKU_SeriesNum=I('post.SKU_SeriesNum');
        //颜色
        $SKU_SeledItem['SKU_Style']=I('post.SKU_Style');
        $SKU_SeledItem['SKU_Style_Cus']=I('post.SKU_Style_Cus');
        $SKU_SeledItem['SKU_Style_Idx']=I('post.SKU_Style_Idx');
         $SKU_StyleName=I('post.SKU_StyleName');
        //规格
        $SKU_SeledItem['SKU_Spec_Idx']=I('post.SKU_Spec_Idx');        
        $SKU_SeledItem['SKU_Spec']=I('post.SKU_Spec');        
        $SKU_SeledItem['SKU_Spec_Cus']=I('post.SKU_Spec_Cus');
        $SKU_SpecName=I('post.SKU_SpecName');
        //图片
        $SKU_Pic=$_POST['UpFilePathInfo']['SKU_Pic'];

            

        //图片保存路径
      
        //判断是否有颜色样式单品选中项并生成Json代码
        $SKU_StyleCount=count($SKU_SeledItem['SKU_Style']);
        
        if($SKU_SeledItem['SKU_Style']!==''){
        
                //配置项信息处理，这里处理的是选择的SKU单品属性项和对应的图片信息
                for($i=0;$i<$SKU_StyleCount;$i++){
                    $thumbPicPath_M='';
                    $thumbPicPath_S='';

                    $SKU_Pic[$i]=$SKU_Pic[$i]=='null'?$new_data['image']:$SKU_Pic[$i];
                    $SKU_Pic[$i]=$SKU_Pic[$i]==''?$new_data['image']:$SKU_Pic[$i];
                    $SKU_Img=$SKU_Pic[$i];
                    //缩略图生成

                    if(!empty($SKU_Pic)){
                        
                        //图片全地址
                        $SKU_Img_Path=$_SERVER['DOCUMENT_ROOT'].$SKU_Pic[$i];
                        //保存地址

                        $SKU_Img=$SKU_Pic[$i];
                       
                        if(file_exists($SKU_Img_Path)){
                            $thumbPicPath_S_Path=$SKU_Img_Path.'-s_thumb.jpg';
                            $thumbPicPath_M_Path=$SKU_Img_Path.'-m_thumb.jpg';
                            $thumbPicPath_S=$SKU_Img.'-s_thumb.jpg';
                            $thumbPicPath_M=$SKU_Img.'-m_thumb.jpg';
                        }

                        //文件名已经存在时跳过
                        if(!file_exists($thumbPicPath_S_Path)&&file_exists($SKU_Img_Path)){
                            getPicThumb($SKU_Img_Path,120,120,1,$thumbPicPath_S_Path);
                        }
                        if(!file_exists($thumbPicPath_M_Path)&&file_exists($SKU_Img_Path)){
                             getPicThumb($SKU_Img_Path,400,400,1,$thumbPicPath_M_Path);   
                        }

                    }
                 

                    $style[]=array(
                        'SKU_Style_Idx'=>$SKU_SeledItem['SKU_Style_Idx'][$i],
                        'defaultValue'=>$SKU_SeledItem['SKU_Style'][$i],
                        'modifyValue'=>$SKU_SeledItem['SKU_Style_Cus'][$i],
                        'SKU_Img'=>$SKU_Img,
                        'SKU_ThumbImg_M'=>$thumbPicPath_M,
                        'SKU_ThumbImg'=>$thumbPicPath_S
                    );
                    //生成添加或者更新时对应sku表中sku_img的图片数据，由于是json，这里需要重新生成一个数组
                    $skuImgData[]=array(
                        'SKU_Img'=>$SKU_Img,
                        'SKU_ThumbImg_M'=>$thumbPicPath_M,
                        'SKU_ThumbImg'=>$thumbPicPath_S
                    );
                }
                $SKU_Info['SKU_Style']=$style;

                
        }else{
            $SKU_Info['SKU_Style']=null;
        }
        
        
      
        //判断是否有规格单品选中项生成Json代码
        $SKU_SpecCount=count($SKU_SeledItem['SKU_Spec']);
        if($SKU_SeledItem['SKU_Spec']!==''){
            for($i=0;$i<$SKU_SpecCount;$i++){
                $spec[]=array('SKU_Spec_Idx'=>$SKU_SeledItem['SKU_Spec_Idx'][$i],
                    'defaultValue'=>$SKU_SeledItem['SKU_Spec'][$i],
                    'modifyValue'=>$SKU_SeledItem['SKU_Spec_Cus'][$i]);
            }
            $SKU_Info['SKU_Spec']=$spec;
        }else{
            $SKU_Info['SKU_Spec']=null;
        }
		
        if($SKU_SeledItem['SKU_Spec']!==''||$SKU_SeledItem['SKU_Style']!==''){
                //处理单品项表单数据，转为数据行，这里以必然出现的表单项为长度进行遍历
                for($i=0;$i<count($SKU_Stock);$i++){
                    $SKU_Price[$i]=$SKU_Price[$i]==''?$new_data['price']:$SKU_Price[$i];
                    $SKU_Price_tuan[$i]=$SKU_Price_tuan[$i]==''?$new_data['price']:$SKU_Price_tuan[$i];

                    $SKU_Stock[$i]=$SKU_Stock[$i]==''?0:$SKU_Stock[$i];
                    $SKU_Form[]=array(
                        'sku_spec'=>$SKU_SpecName[$i],
                        'sku_style'=>$SKU_StyleName[$i],
                        'sku_stock'=>$SKU_Stock[$i]==''?$new_data['num']:$SKU_Stock[$i],
                        'sku_price'=>$SKU_Price[$i],
                        'sku_price_tuan'=>$SKU_Price_tuan[$i],
                        'sku_series'=>$SKU_SeriesNum[$i]
                    );
                }
                $SKU_Info['SKU_Form']=$SKU_Form;

                //加入SKU单品项更新数据
                $new_data['shop_sku']=json_encode($SKU_Info);
         }else{
            $SKU_Info['SKU_Form']=null;

            //加入SKU单品项更新数据
            $new_data['shop_sku']=null;
        }
        
        if($id){
            $flag1=$shop->where(' id = '.$id)->save($new_data);
		
            $new_data1['shop_id'] =   $id;
            $rs=$ShopContent->where(' shop_id = '.$id)->find();
            if($rs){
               $flag2= $ShopContent->where(' shop_id = '.$id)->save($new_data1);
            }else{
               $flag2= $ShopContent->add($new_data1);
            }	
        }else{
            $new_data['addtime']    =   time();
            $flag1=$shop->add($new_data);
            
            $new_data1['shop_id'] = $flag1;
            $flag2=$ShopContent->add($new_data1);
        }

       
       
       
        $this->SKU_model=M('shop_sku');
        //开启事务批量插入数据
        $this->SKU_model->startTrans();
      
        //如果存在SKU单品数据，则为其添加对应所属的商品ID
        if(count($SKU_Form)>0){
				
                foreach ($SKU_Form as $key => $value) {
                     $map['shop_id']=$new_data1['shop_id'];
                     $map['sku_idx']=$key;
					 
                    $rs_sku= $this->SKU_model->where($map)->find();

                    //判断是插入数据还是编辑更新数据
                    if(!$rs_sku){
                        $value['shop_id']=$new_data1['shop_id'];
                        $value['sku_idx']=$key;
                        $value['sku_img']=!empty($skuImgData[$key])?json_encode($skuImgData[$key]):null;
                        $skuResult=$this->SKU_model->add($value);
                       
                    }else{
                        $value['sku_img']=!empty($skuImgData[$key])?json_encode($skuImgData[$key]):null;
                        $skuResult=$this->SKU_model->where(array('shop_id'=>$new_data1['shop_id'],'sku_idx'=>$key,'sku_id'=>$rs_sku['sku_id']))->save($value);

                    }
                 
                  
                }
                if($skuResult===false){
                    $this->SKU_model->rollback();
                   
                    echo '0|||保存商品失败';die();
                }else{
                    $this->SKU_model->commit();
                   
                     //不存在SKU单品数据时直接提交商品数据
                    echo '0|||保存商品成功|||/Shop/index/';die();
                }
           
        
        }else{
            //不存在SKU单品数据时直接提交商品数据
            echo '0|||保存商品成功|||/Shop/index/';die();
        }
          
      
    }

    /**
     * 禁用
    */
    function delete(){
        $shop   =   D('shop');
        $id     =   $_GET['id'];
        $data['ishidden'] =   $_GET['ishidden'];
		
        $flag   =   $shop->where(' id = '.$id)->save($data);
       if( $flag !== false ){
            echo '操作成功';die();
        }else{
            echo '操作失败';die();
        }
       
    }
  /**
     * 推荐
    */
    function nice(){
        $MallTicket   =   D('MallTicket');
        $id     =   $_GET['id'];
        $data['isindex'] =   $_GET['isnice'];
        $flag   =   $MallTicket->where(' id = '.$id)->save($data);
        if( $flag !== false ){
            echo '操作成功';die();
        }else{
            echo '操作失败';die();
        }
      
    }

      /**
     * 复制配置属性
     */
    function copyConfigHtml()
    {
        $ticketType = D('TicketType');
        $keywords = I('get.keywords');
        $where = ' ishidden = 0';
        if($keywords){
            $where .= '   AND name LIKE "%' . $keywords . '%"';
            $ticketType    =   $ticketType->field('id,name,bid,bids')->where($where)->find();
            $key_id=explode(',',$ticketType['bids']);
            $ticketTypeArray = M('ticket_type')->field('id,name,bid,bids')->where('bids LIKE "%'.$key_id[0].'%" AND  ishidden = 0')->select();
        }else{
            $ticketTypeArray    =   $ticketType->field('id,name,bid,bids')->where($where)->select();
        }
       

        $this->assign('ticketTypeArray',$ticketTypeArray);

        $classTree = catetree($ticketTypeArray);
        $this->assign('classTree',$classTree);
        
        $this->assign('type_id', I('get.type_id'));

        $this->display();
    }
    function zuzhuang(){
        if( I('get.type') == 'save' ){
            $this->zuzhuangSave();
        }else{
           $this->display();
        }
    }

    function zuzhuangSave(){
        $zuzhuangString    =   I('get.zuzhuangString');
        $array =   explode(',',$zuzhuangString);
        $string    =   getCount($array);
        $count =   count(explode(',', $string));
        echo $count.'|||'.$string;
    }


      /**
     * 商品分类管理
     */
    function ticketTypeList()
    {
        $ticketType = D('TicketType');
        $where = 'ishidden = 0';
        $where .= I('get.name') ? ' AND name LIKE "%' . I('get.name') . '%"' : '';
        $count = $ticketType->where($where)->count();
        $Page = new \Think\Page($count, 25); // 实例化分页类 传入总记录数
        $show = $Page->show(); // 分页显示输出
        $array = $ticketType
            ->where($where)
            ->order('bids ASC')
            ->limit($Page->firstRow . ',' . $Page->listRows)
            ->select();

        $this->assign('page', $show); // 赋值分页输出
        $this->assign('array', $array);
        $this->assign('title', '商品类型列表页');
        $this->display();
    }

    /**
     * 商品类型添加
     */
    function ticketTypeAdd()
    {
        $brand = D('Brand');
        $ticketType = D('TicketType');
       
        if ($_GET['id']) {
            $this->assign('title', '修改商品类型');
        } else {
            $this->assign('title', '添加商品类型');
        }
        $current = $ticketType->where('id = ' . $_GET['id'])->find();
        $this->assign('current', $current);
        $bcurrent = $ticketType->where(' id = "' . $current['bid'] . '"')->find();
        $array = getTypes();
        $this->assign('array', $array);

        //商品类型
        $shop_type=M('shop_type');
        $shop_types=$shop_type->where('ishidden=0')->select();
        $this->assign('shop_types', $shop_types);
        // 获取品牌信息
        $whereFlag = ' ishidden = 0 ';
        $whereFlag .= $bcurrent['bindBrand'] ? ' AND id IN (' . $bcurrent['bindBrand'] . ') ' : '';
        $brandArray = $brand->where($whereFlag)->select();
        $this->assign('brandArray', $brandArray);
       
        $this->display();
    }

    /**
     * 添加保存
     */
    function ticketTypeSave()
    {
        $ticketType = M('TicketType');

        $id = $_POST['id'];
        $data['id'] = $_POST['id'];
        $new_data = array_diff_key($_POST, $data);
        $new_data['name'] = I('post.name');
        $new_data['shortname'] = I('post.shortname');
        $new_data['keywords'] = I('post.keywords');
        $new_data['description'] = I('post.description');
        $new_data['sort'] = I('post.sort');
        $new_data['bid'] = I('post.bid');
        $new_data['type_id'] = I('post.type_id');
        
        $new_data['bindBrand'] = I('post.bindBrand') ? implode(',', I('post.bindBrand')) : '';
        // 修改上级栏目为非终极栏目
        $ticketType->where(' id = ' . I('post.bid'))->save(array('is_end' => '0'));

        if(I('post.ishidden')){
            $new_data['ishidden']=0;
        }else{
            $new_data['ishidden']=1;
        }
        
        $new_data['addtime'] = time();
        if($id){
        	$rs=$ticketType->where("bid=".$id)->select();
        	if(!$rs){
        		$new_data['is_end'] = 1;
        	}
            $new_data['id']=$id;
            $barray = $ticketType->field('bids')->where(' id = ' . I('post.bid'))->find();
            $new_data['bids'] = $barray['bids'] . ',' . $id;
            $rs=$ticketType->save($new_data);
         }else{
         	$new_data['is_end'] = 1;
            $rs=$ticketType->add($new_data);
            $data['id']=$rs;
           	$barray = $ticketType->field('bids')->where(' id = ' . I('post.bid'))->find();
            $data['bids'] = $barray['bids'] . ',' . $data['id'];
            $rs=$ticketType->save($data);
        }
        if($rs){
        	$ticketTypeArrays=$ticketType->select();
        	foreach($ticketTypeArrays as $key =>$value){
        		if($value['is_end']==1){
        			 $rss=$ticketType->where("bid=".$value['id'])->select();
	        		  if($rss){
	        		  	$maps['id']=$value['id'];
	        		  	$maps['is_end']=0;
	        		  	$ticketType->save($maps);
	        		  }
        		}
        		 
        	}
            echo "0|||操作成功|||/Shop/ticketTypeList.html";
        }else{
             echo "0|||操作失败";
        }
        
    }

    //添加属性
    function addAttribute($typeArray){
        $ticketConfig = D('TicketConfig');
        $typeAttribute = D('TypeAttribute');
        if($typeArray['bid']){
            $attributeid = $typeAttribute->field('id')->where('supertypeid = '.$typeArray['bid'])->find();

            $attributeArray = $typeAttribute->field('typename')->where('find_in_set('.$attributeid['id'].',supertypeid)')->select();


            $attributeid['id'];
        }
        foreach($attributeArray as $k=>$v){
            $data = array();
            $data['title'] = $v['typename'];
            $data['type_id'] = $typeArray['id'];
            $data['content'] = ' ';
            $data['user_id'] = $typeArray['user_id'];
            $data['is_write'] = '0';
            $data['sort'] = '0';
            $data['addtime'] = time();
            $ticketConfig->add($data);
        }

        return true;

    }

    /**
     * 禁用
     */
    function ticketTypeDelete()
    {
        $ticketType = D('TicketType');
        $id = $_GET['id'];
        $data['ishidden'] = '1';

        $current = $ticketType->field('id,bid,ishidden')
            ->where(' id = ' . $id)
            ->find();
        $arrayFlag = $ticketType->field('id')
            ->where(' bid = ' . $current['bid'] . ' AND ishidden = 0 AND id <> ' . $id)
            ->find();
        $new_data['is_end'] = $arrayFlag ? '0' : '1';
        $flag = $ticketType->where(' id = ' . $current['bid'])->save($new_data);
        $flag = $ticketType->where(' id = ' . $id)->save($data);


        echo '0|||删除成功|||/Shop/ticketTypeList/';
        die();
    }




      /**
     * 属性配置列表
     */
    function configList()
    {
        $ticketConfig = D('TicketConfig');
        $where = 'ishidden = 0 AND type_id = ' . I('get.type_id');
        $array = $ticketConfig->where($where)
            ->order('id DESC')
            ->select();
        $this->assign('array', $array);
        $this->assign('title', '属性配置列表页');
        $this->display();
    }

    /**
     * 操作属性配置
     */
    function configAdd()
    {
        $ticketConfig = D('TicketConfig');
        $current = $ticketConfig->where('id = ' . $_GET['id'])->find();
        $this->assign('current', $current);
        $this->assign('type_id', I('get.type_id'));
        $this->assign('title', '操作属性配置');
        $this->display();
    }

    /**
     * 添加保存
     */
    function configSave()
    {
        $ticketConfig = D('TicketConfig');
        $id = $_POST['id'];
        $data['title'] = I('post.title');
        $data['content'] = I('post.content');
        $data['type_id'] = I('post.type_id');
        $data['is_write'] = I('post.is_write');
        $data['sort'] = I('post.sort',0);
        if ($id) {
            $flag = $ticketConfig->where(' id = ' . $id)->save($data);
        } else {
            $data['user_id'] = session('user_id');
            $data['addtime'] = time();
            $flag = $ticketConfig->add($data);
        }
        if ($flag !== false) {
            echo '0|||操作成功|||/Shop/configList/type_id/' . $data['type_id'];
            die();
        } else {
            echo '0|||操作失败|||reload';
            die();
        }
        // urlSkip($flag,'/Area/configList/type_id/'.I('post.type_id'),1);
    }

    /**
     * 禁用
     */
    function configDelete()
    {
        $ticketConfig = D('TicketConfig');
        $id = $_GET['id'];
        $data['ishidden'] = '1';

        $flag = $ticketConfig->where(' id = ' . $id)->save($data);

        if ($flag !== false) {
            echo '0|||操作成功|||/Shop/configList/type_id/' . I('get.type_id');
            die();
        } else {
            echo '0|||操作失败';
            die();
        }
    }


    /**
     * 商品品牌管理
     */
    function brandList()
    {
        $brand = D('Brand');
        $count = $brand->count();
        $Page = new \Think\Page($count, 15); // 实例化分页类 传入总记录数
        $show = $Page->show(); // 分页显示输出
        $array = $brand
            ->order('id DESC')
            ->limit($Page->firstRow . ',' . $Page->listRows)
            ->select();
        $this->assign('page', $show); // 赋值分页输出
        $this->assign('array', $array);
        $this->assign('title', '品牌列表页');
        $this->display();
    }

    /**
     * 品牌添加
     */
    function brandAdd()
    {
        if ($_GET['id']) {
            $this->assign('title', '修改品牌');
        } else {
            $this->assign('title', '添加品牌');
        }
        $brand = D('Brand');
        $current = $brand->where('id = ' . $_GET['id'])->find();
        $this->assign('current', $current);
     
        $this->display();
    }

    /**
     * 添加保存
     */
    function brandSave()
    {
        $brand = D('Brand');
        $id = $_POST['id'];
        // 添加无需添加字段
        $data['name'] = $_POST['name'];
        $data['sort'] = I('post.sort', '0');
        $data['image'] = I('post.UpFilePathInfo');
        if(I('post.ishidden')){
            $data['ishidden'] = 0; 
        }else{
            $data['ishidden'] = 1; 
        }
        
        if ($id) {
            $flag = $brand->where(' id = ' . $id)->save($data);
        } else {
            $data['addtime'] = time();
            $flag = $brand->add($data);
        }
        echo '0|||操作成功|||/Shop/brandList/';
       
    }

    /**
     * 禁用
     */
    function brandDelete()
    {
        $brand = D('Brand');
        $id = I('get.id',0);
        $data['ishidden'] = I('get.ishidden',0);

        $flag = $brand->where(' id = ' . $id)->save($data);

        if ($flag !== false) {
            echo '0|||提交成功|||/Shop/brandList/';
            die();
        } else {
            echo '0|||提交失败';
            die();
        }
    }

    //创建SKU表单html代码

    private function CreateSKUView(){
        $i=0;
        $colorCode='';
        $SpecCode='';
        $SKU_Style=C('GOODS_COLOR');
        $SKU_Spec=C('GOODS_SPEC');

        //取出用户数据，一个是勾选的单品项属性,这个数据解析交给客户端处理，第二个是单品项的对应数据
        $seledSKUOption=json_encode(array('SKU_Color'=>array('blue'=>'蓝色','black'=>'黑色'),'SKU_Spec'=>array('SPEC-2'=>'规格二')));
        $SKU_Data;
        //根据用户数据生成视图代码


        foreach ($SKU_Style as $key => $value) {
            $colorCode.='<label class="checkbox-inline"><input name="SKU_Style[]" value="'
            .$value.'" type="checkbox" data-tag="'.$key.'" data-sku="SKU_Style" ><span>'.$value.'</span>
            <input type=hidden value="'.$value.'" data-tag="modifyValue">
            <input type=hidden value="'.$i.'" data-tag="idx"></label>';
            $i++;
        }

        $i=0;

        foreach ($SKU_Spec as $key => $value) {
            $SpecCode.='<label class="checkbox-inline"><input name="SKU_Spec[]" value="'
            .$value.'" type="checkbox" data-tag="'.$key.'" data-sku="SKU_Spec" ><span>'.$value.'</span>
            <input type=hidden value="'.$value.'" data-tag="modifyValue">
            <input type=hidden value="'.$i.'" data-tag="idx"></label>'; 
            $i++;       
        }

        $colorCode='<div id="SKU_Style" class="checkbox" data-skutype="sub">'.$colorCode.'</div>';
        $SpecCode='<div id="SKU_Spec" class="checkbox" data-skutype="main">'.$SpecCode.'</div>';
        $this->assign('seledSKUOption',$seledSKUOption);

        return $colorCode.$SpecCode;
    }

    // 广告开始
    // 广告管理首页
    public function sliderAD(){
        $keywords=I('post.keywords');
        $status=I('post.ad_status');
        $ad_type=I('post.ad_type');
         if(!empty($keywords)){
            $where['ad_name']=array('like','%'.$keywords.'%');
        }
        if($status>=0&&$status!=''){
            $where['ad_status']=$status;
        }

         if($ad_type>=0&&$ad_type!=''){
            $where['ad_type']=$ad_type;
        }
        $count=$this->ad_model->where($where)->count();
        $page=new \Think\Page($count,10);
        $sliderAD=$this->ad_model->where($where)->limit($page->firstRow,$page->listRows)->order('listorder')->select();
        foreach ($sliderAD as $key => $value) {
            if($value['ad_type']==1){
                $sliderAD[$key]['ad_type_name']='幻灯类';
            }
            if($value['ad_type']==2){
                $sliderAD[$key]['ad_type_name']='商品类';
            }
             if($value['ad_type']==3){
                $sliderAD[$key]['ad_type_name']='品牌类';
            }
             if($value['ad_type']==4){
               $sliderAD[$key]['ad_type_name'] ='店铺类';
            }
        }
        $this->assign('title','广告管理');
        $this->assign('adData',$sliderAD);
        $this->assign('keywords',$keywords);
        $this->assign('status',$status);
        $this->assign('ad_type',$ad_type);
        $this->assign('page',$page->show());
        $this->display();   
    }

   

    // 广告大类排序
    public function listorders() {

        
        $ids = $_POST['listorders'];

        foreach ($ids as $key => $r) {
            $data['listorder'] = $r;
            $status=$this->ad_model->where(array('id' => $key))->save($data);
        }
        if ($status) {
            $this->success("排序更新成功！");
        } else {
            $this->error("没用数据更新！");
        }
    }

    // 添加广告类(统一使用一个页面)
    public function add_ad(){
        if($_POST){
            $data=I('post.');
            if($data['ad_name']==''){
                echo "0|||请填写广告名称";
                die;
            }
           
            if($data['ad_container']==''){
                echo "0|||请填写广告容器标识";
                die;
            }
            if($this->ad_model->add($data)===false){
                echo '0|||添加广告失败：'.$this->ad_model->getError();
                die;
              
            }else{
                echo '0|||添加广告成功！|||reload';
                die;
              
            }
          
        }else{
            $ad_type=I('get.ad_type',0,'intval');
            $this->assign('title','添加广告');
            $this->assign('ad_type',$ad_type);
            $this->display();
        }
        
    }

    // 编辑广告类
    public function editAD(){
        if($_POST){
            $id=I('get.id',0,'intval');
            if(!empty($id)){
                $data=I('post.');
                if($data['ad_name']==''){
                    echo "0|||请填写广告名称";
                    die;
                }
               
                if($data['ad_container']==''){
                    echo "0|||请填写广告容器标识";
                    die;
                }
                if($this->ad_model->where(array('id'=>$id))->save($data)===false){
                    echo '0|||编辑保存广告失败：'.$this->ad_model->getError();
                    die;
                }else{
                    echo '0|||编辑广告成功！|||reload';
                    die;
                   
                }
                
            }

        }else{  
            $id = I("get.id",0,'intval');
            $ad_data=$this->ad_model->where(array('id'=>$id))->find();
             $this->assign('title','编辑广告');
            $this->assign('adData',$ad_data);
            $this->display();
        }
    }

       // 删除广告类
    function deleteAD(){
        if(isset($_GET['id'])){
            $id = I("get.id",0,'intval');
            if ($this->ad_model->where(array('id'=>$id))->delete()!==false) {
                $this->success("删除成功！");
            } else {
                $this->error("删除失败！");
            }
        }
    }

     //管理广告
    public function manageSliderAD(){
        $id=I('get.id',0,'intval');
        $ad_name=I('get.ad_name');

        $adData=$this->ad_model->where(array('id'=>$id))->find();
        if($adData===false){
            $this->error('无法进入广告管理页面：'.$this->ad_model->getError());
        }
        if($adData['ad_type']==1){
            $adData['ad_type_name']='幻灯类';
        }
        if($adData['ad_type']==2){
            $adData['ad_type_name']='商品类';
        }
         if($adData['ad_type']==3){
            $adData['ad_type_name']='品牌类';
        }
         if($adData['ad_type']==4){
            $adData['ad_type_name'] ='店铺类';
        }
        $this->assign('title','幻灯广告管理');
        $this->assign('adData',$adData);
        $this->assign('ad_name',$ad_name);
        $this->display();
    }

    //广告列表项排序
    public function adItemOrders(){
        $id=I('get.id');
        $orderItem=I('post.listorders');
       // file_put_contents('2.txt', var_export($_POST,true));
        $adData=$this->ad_model->where(array('id'=>$id))->field('ad_data')->find();
        $adData['ad_data']=json_decode($adData['ad_data'],true);

        foreach ($orderItem as $key => $value) {
            $adData['ad_data']['AdItem'][$key]['listorder']=$value;
        }
       // file_put_contents('1.txt', var_export($adData,true));
        $adData['ad_data']=json_encode($adData['ad_data']);

        $status=$this->ad_model->where(array('id'=>$id))->save($adData);

        if ($status!==false) {
           
            $this->success("排序更新成功！");
        } else {
            $this->error("排序更新失败！");
        }       
    }


    //删除幻灯广告项（代码和其它广告的删除代码一样，如果确定不更改数据结构可以合而为一）
    public function deleteSliderAdItem(){
        $id=I('post.id',0,'intval');
        $adKey=explode(',',I('post.adKey'));
        
        $adData=$this->ad_model->where(array('id'=>$id))->field('ad_data')->find();
        if(!empty($adData)){
            $adData['ad_data']=json_decode($adData['ad_data'],true);
            if(is_array($adKey)){
                foreach ($adKey as $key => $value) {
                    unset($adData['ad_data']['AdItem'][$value]);
                }
                rsort($adData['ad_data']['AdItem']);
            }else{
                array_splice($adData['ad_data']['AdItem'],$adKey,1);
            }

            $adData['ad_data']=json_encode($adData['ad_data']);
            if($this->ad_model->where(array('id'=>$id))->save($adData)===false){
                $this->ajaxReturn(array('status'=>0,'error'=>'更新广告数据失败！'.$this->ad_model->getError()));
            }else{
                
                $this->ajaxReturn(array('status'=>1,'data'=>$deleteIdx));
            }
        }else{
            $this->ajaxReturn(array('status'=>0,'error'=>'未查询到对应的广告数据！'));
        }
    }



   

    //添加广告项
    public function addSliderAdItem(){
        $id=I('get.id',0,'intval');
        $adData=$this->ad_model->where(array('id'=>$id))->find();
        $ad_name=I('get.ad_name');
        $this->assign('id',$id);
        $this->assign('ad_name',$ad_name);
        $this->assign('ad_type',$adData['ad_type']);
        $this->assign('title','添加幻灯广告项');
        $this->display();
    }

    //编辑广告项
    public function editSliderAdItem(){
        $adKey=I('get.adKey',0,'intval');
        $id=I('get.id',0,'intval');
        $ad_name=I('get.ad_name');

        $adData=$this->ad_model->where(array('id'=>$id))->find();
        $this->assign('adData',$adData);
        $this->assign('id',$id);
        $this->assign('adKey',$adKey);
        $this->assign('ad_name',$ad_name);
        $this->assign('ad_type',$adData['ad_type']);
        $this->assign('title','编辑幻灯广告项');
        $this->display();
    }

    public function postSliderAD(){
        $postType=I('post.postType');
        $adKey=I('post.adKey',0,'intval');
        $data=I('post.');
        $id=I('get.id',0,'intval');

        if(empty($data['ad_title'])){
            echo "0|||必须填写广告主标题！";die();
        }

        if(empty($data['UpFilePathInfo'])){
            echo "0|||必须上传广告图片！";die();
    
        }

        $adData=$this->ad_model->where(array('id'=>$id))->field('ad_data')->find();
        $adData['ad_data']=json_decode($adData['ad_data'],true);
       

        if($postType=='add'){
            $adData['ad_data']['AdItem'][]=$data;
        }
        if($postType=='edit'){
            $adData['ad_data']['AdItem'][$adKey]=$data;
        }
       
        $adData['ad_data']=json_encode($adData['ad_data']);
        $this->ad_model->where(array('id'=>$id))->save($adData);

   
        if($postType=='add'){
            echo "0|||成功添加广告！";die();
        }else{
            echo "0|||成功编辑广告！";die();
        }
       
    }

    function get_shop(){
        if($_POST){
            $id=I('post.id');
            $shop=M('shop');
            $rs=$shop->field('title,image,price,oprice')->find($id);
            $rs['url']=U('shop/index',array('id' => $id));
            $this->ajaxReturn($rs);
        }
    }

    function get_store(){
        if($_POST){
            $id=I('post.id');
            $store=M('store');
            $store_template=M('store_template');
            $rs=$store->field('title')->find($id);
            $rs_template=$store_template->field('portrait')->where("store_id=$id")->find($id);
            $data['url']=U('store/index',array('id' => $id));
            $data['title']=$rs['title'];
            $data['image']=$rs_template['portrait'];
            $this->ajaxReturn($data);
        }
    }
    function get_brand(){
        if($_POST){
            $id=I('post.id');
            $brand=M('brand');
            $rs=$brand->field('name,image')->find($id);
            $rs['url']=U('brand/index',array('id' => $id));
            $this->ajaxReturn($rs);
        }
    }


    function attributelist(){
        $shop_type=M('shop_type');
        $ticket_config=M('ticket_config');
        $array=$shop_type->where('ishidden=0')->order('sort desc')->select();
        foreach ($array as $key => $value) {
            $rs=$ticket_config->where('type_id='.$value['id'])->select();
            $attributename="";
            foreach ($rs as $k => $v) {

                $attributename=$attributename.$v['title'].',';

            }
            $array[$key]['attributename']= $attributename;
        }

        $this->assign('array',$array);
        $this->assign('title','商品类型');
        $this->display();
    }

    
     function attributeAdd(){
        if($_GET['id']){
            $shop_type=M('shop_type');
            $current=$shop_type->find($_GET['id']);
             $this->assign('current',$current);
        }
        $this->assign('title','添加商品类型');
        $this->display();
    }

     function attributeSave(){
       $data=I('post.');
       $shop_type=M('shop_type');
       if($data['ishidden']){
         $data['ishidden']=0;
       }else{
         $data['ishidden']=1;
       }
       if($data['id']){
        $rs=$shop_type->save($data);
       }else{
        $rs=$shop_type->add($data);
       }

       if($rs){
          echo "0|||添加成功！";
       }else{
          echo "0|||添加失败！";
       }
    }
  
  function pt_shop(){
        $nowtime=time();
        $shop=M('shop');
        $count=$shop->where("ishidden=0 and tuanselect=1 and tuanz_starttime<$nowtime and tuanz_endtime>$nowtime")->count();
    	$Page = new \Think\Page ($count,15); // 实例化分页类 传入总记录数
		$Page->setConfig('header','条记录');
	    $Page->setConfig('prev','上一页');
	    $Page->setConfig('next','下一页');
		$show = $Page->show(); // 分页显示输出
 		$rs=$shop->where("ishidden=0 and tuanselect=1 and tuanz_starttime<$nowtime and tuanz_endtime>$nowtime")->limit($Page->firstRow.','.$Page->listRows)->order('tuan_order desc')->select();
        $this->assign('page',$show);
        $this->assign('title','拼团管理');
        $this->assign('rs',$rs);
     	$this->display();
  }
  
  function pt_shop_order(){
  	$data=I('post.listorders');
    foreach($data as $key=>$value){
    	 $shop=M('shop');
         $info['id']=$key;
         $info['tuan_order']=$value;
         $shop->save($info);
    }
    $this->redirect('shop/pt_shop');
  }

  

}
